package com.dingup.homework.service.impl;

import com.dingup.api.bean.page.PageData;
import com.dingup.homework.bean.DO.CorrectTeacher;
import com.dingup.homework.bean.DO.HwHomeworkDO;
import com.dingup.homework.bean.DO.HwHomeworkRecordDO;
import com.dingup.homework.bean.DO.HwHomeworkTeacherCorrectDO;
import com.dingup.homework.bean.DTO.TeacherCorrectDTO;
import com.dingup.homework.bean.HomeworkQuestion;
import com.dingup.homework.dao.HwHomeworkMapper;
import com.dingup.homework.dao.HwHomeworkRecordsMapper;
import com.dingup.homework.dao.HwHomeworkTeacherCorrectMapper;
import com.dingup.homework.enums.HomeworkRecordStatusEnum;
import com.dingup.homework.enums.HomeworkStatusEnum;
import com.dingup.homework.enums.QuestionTypeEnum;
import com.dingup.homework.feign.client.user.UserFeignClient;
import com.dingup.homework.service.HwHomeworkRecordsService;
import com.dingup.homework.service.TeacherCorrectService;
import com.dingup.homework.util.PageDataUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/11/8.
 */
@Service
public class TeacherCorrectServiceImpl implements TeacherCorrectService {

    private static final Logger logger = LoggerFactory.getLogger(TeacherCorrectServiceImpl.class);

    @Autowired
    private HwHomeworkTeacherCorrectMapper hwHomeworkTeacherCorrectMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private HwHomeworkRecordsService hwHomeworkRecordsService;
    @Autowired
    private HwHomeworkMapper hwHomeworkMapper;
    @Autowired
    private HwHomeworkRecordsMapper hwHomeworkRecordsMapper;

    @Override
    public Boolean insert(HwHomeworkTeacherCorrectDO bean) {

        if (StringUtils.isNotEmpty(bean.getStudentId())) {
            bean.setStudentName(userFeignClient.getUserNameByUserId(bean.getStudentId()));
        }
        if (StringUtils.isNotEmpty(bean.getTeacherId())) {
            bean.setTeacherName(userFeignClient.getUserNameByUserId(bean.getTeacherId()));
        }
        Integer res = hwHomeworkTeacherCorrectMapper.insertSelective(bean);
        if (res == null || res.intValue() == 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void insert(Integer homeworkRecordId, String examId, Date endTime) throws Exception {
        HwHomeworkRecordDO recordDO = hwHomeworkRecordsService.getById(homeworkRecordId);
        if (recordDO == null) {
            throw new Exception("无效的作业RecordId");
        }
        HwHomeworkDO homeworkDO = hwHomeworkMapper.getById(recordDO.getHomeworkId());
        if (homeworkDO == null) {
            throw new Exception("无效的作业homeworkId");
        }
        HwHomeworkTeacherCorrectDO correctDO = new HwHomeworkTeacherCorrectDO();
        String studentId = recordDO.getStudentId();
        String studentName = null;
        if (StringUtils.isNotEmpty(studentId)) {
            studentName = userFeignClient.getUserNameByUserId(studentId);
            correctDO.setStudentId(studentId);
            correctDO.setStudentName(studentName);
        }
        correctDO.setStatus(HomeworkStatusEnum.UNFINISHED);
        correctDO.setHomeworkId(homeworkDO.getId());
        correctDO.setHomeworkRecordId(recordDO.getId());
        correctDO.setCreateTime(new Date());
        correctDO.setEndTime(endTime);
        correctDO.setExamId(examId);
        if (homeworkDO.getCorrectTeacher() != null) {
            insertCorrectTeacherRecords(homeworkDO.getCorrectTeacher(), correctDO, homeworkDO);
        }
    }

    @Override
    public void insertBatch(HwHomeworkDO hwHomeworkDO) throws Exception {
        if (hwHomeworkDO.getId() == null || hwHomeworkDO.getStudentIds() == null) {
            throw new Exception("作业id或学生id位空");
        }
        List<HwHomeworkRecordDO> records = hwHomeworkRecordsMapper.getByHomeworkId(hwHomeworkDO.getId());
        insert(hwHomeworkDO.getId(), null, null);
    }

    private void insertCorrectTeacherRecords(CorrectTeacher correctTeacher, HwHomeworkTeacherCorrectDO correctDO, HwHomeworkDO homework) {
        try {
            HwHomeworkTeacherCorrectDO record = correctDO.clone();
            List<HomeworkQuestion> questionList = homework.getQuestionList();
            Map<QuestionTypeEnum, List<HomeworkQuestion>> groupMap = questionList.stream().collect(Collectors.groupingBy(HomeworkQuestion::getQuestionType));
            List<HomeworkQuestion> writing = groupMap.get(QuestionTypeEnum.WRITING);
            List<HomeworkQuestion> speaking = groupMap.get(QuestionTypeEnum.SPEAKING);
            List<HomeworkQuestion> all = groupMap.get(QuestionTypeEnum.ALL);
            List<HomeworkQuestion> subjective = groupMap.get(QuestionTypeEnum.SUBJECTIVE);
            List<HwHomeworkTeacherCorrectDO> needInsert = new ArrayList<>();
            if (!CollectionUtils.isEmpty(writing)) {
                record.setTeacherId(correctTeacher.getTeacherForWriting());
                List<HwHomeworkTeacherCorrectDO> writingDOs = getTeacherCorrect(writing, record, QuestionTypeEnum.WRITING);
                needInsert.addAll(writingDOs);
            }
            if (!CollectionUtils.isEmpty(speaking)) {
                record.setTeacherId(correctTeacher.getTeacherForSpeaking());
                List<HwHomeworkTeacherCorrectDO> speakingDOs = getTeacherCorrect(speaking, record, QuestionTypeEnum.SPEAKING);
                needInsert.addAll(speakingDOs);
            }
            if (!CollectionUtils.isEmpty(subjective)) {
                record.setTeacherId(correctTeacher.getTeacherForSubjective());
                List<HwHomeworkTeacherCorrectDO> subjectiveDOs = getTeacherCorrect(subjective, record, QuestionTypeEnum.SUBJECTIVE);
                needInsert.addAll(subjectiveDOs);
            }
            if (!CollectionUtils.isEmpty(all)) {
                record.setTeacherId(correctTeacher.getTeacherForWriting());
                List<HwHomeworkTeacherCorrectDO> writingDOs = getTeacherCorrect(all, record, QuestionTypeEnum.WRITING);
                needInsert.addAll(writingDOs);
                record.setTeacherId(correctTeacher.getTeacherForSpeaking());
                List<HwHomeworkTeacherCorrectDO> speakingDOs = getTeacherCorrect(all, record, QuestionTypeEnum.SPEAKING);
                needInsert.addAll(speakingDOs);
            }
            if (!CollectionUtils.isEmpty(needInsert)) {
                hwHomeworkTeacherCorrectMapper.insertList(needInsert);
            }
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private List<HwHomeworkTeacherCorrectDO> getTeacherCorrect(List<HomeworkQuestion> questions, HwHomeworkTeacherCorrectDO correct, QuestionTypeEnum questionTypeEnum) {
        List<HwHomeworkTeacherCorrectDO> res = new ArrayList<>();
        questions.forEach(
                w -> {
                    try {
                        HwHomeworkTeacherCorrectDO writingCorrect = correct.clone();
                        writingCorrect.setType(questionTypeEnum);
                        writingCorrect.setSubjectName(w.getSubjectName());
                        //writingCorrect.setQuestionIndex(w.getIndex());
                        writingCorrect.setArticleNum(w.getArticleNum());
                        writingCorrect.setOtherData(w.getTextDescription());
                        //将写作和听力类型的title存入otherData中
                        if (StringUtils.isEmpty(writingCorrect.getOtherData())) {
                            writingCorrect.setOtherData(w.getTitle());
                        }
                        res.add(writingCorrect);
                    } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
                    }
                }
        );
        return res;
    }
    @Override
    public PageData<TeacherCorrectDTO> getTeacherCorrectList(String teacherId,
                                                             String query,
                                                             Boolean ifCorrect,
                                                             Integer page,
                                                             Integer rows) {
        HomeworkStatusEnum statusEnum = HomeworkStatusEnum.UNCORRECTED;
        if (ifCorrect) {
            statusEnum = HomeworkStatusEnum.CORRECTED;
        }
        PageHelper.startPage(page, rows);
        PageHelper.orderBy(" create_time desc ");
        List<TeacherCorrectDTO> list = hwHomeworkTeacherCorrectMapper.getCorrectList(teacherId, query, statusEnum);
        PageInfo<TeacherCorrectDTO> pageInfo = new PageInfo<>(list);
        PageData<TeacherCorrectDTO> res = PageDataUtil.getPageData(pageInfo);
        return res;
    }

    @Override
    public HwHomeworkTeacherCorrectDO getById(Integer id) {
        HwHomeworkTeacherCorrectDO res = hwHomeworkTeacherCorrectMapper.selectByPrimaryKey(id);
        return res;
    }

    @Override
    public void updateCorrectHomeworkStatus(Integer homeworkTeacherStudentId, HomeworkStatusEnum status) {
        HwHomeworkTeacherCorrectDO param = new HwHomeworkTeacherCorrectDO();
        param.setId(homeworkTeacherStudentId);
        param.setStatus(status);
        hwHomeworkTeacherCorrectMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public void updateCorrectHomeworkStatus(Integer homeworkRecodeId, QuestionTypeEnum type, HomeworkStatusEnum status) {
        logger.info("老师批改,修改作业状态 homeworkRecodeId={},type={},status={}", homeworkRecodeId, type, status);
        hwHomeworkTeacherCorrectMapper.updateStatusByHomeworkRecordId(homeworkRecodeId, type, HomeworkStatusEnum.CORRECTED);
        HwHomeworkRecordDO recordDO = new HwHomeworkRecordDO();
        recordDO.setId(homeworkRecodeId);
        recordDO.setStatus(HomeworkRecordStatusEnum.CORRECTED);
        hwHomeworkRecordsService.update(recordDO);
    }

    @Override
    public HwHomeworkTeacherCorrectDO getByBean(HwHomeworkTeacherCorrectDO bean) {
        HwHomeworkTeacherCorrectDO res = hwHomeworkTeacherCorrectMapper.selectOne(bean);
        return res;
    }

    @Override
    public void updateCorrectTeacher(Integer id, String teacherId) {
        String teacherName = userFeignClient.getUserNameByUserId(teacherId);
        HwHomeworkTeacherCorrectDO param = new HwHomeworkTeacherCorrectDO();
        param.setId(id);
        param.setTeacherId(teacherId);
        param.setTeacherName(teacherName);
        hwHomeworkTeacherCorrectMapper.updateByPrimaryKeySelective(param);
    }

    @Override
    public void updateStatusWhileUpdateHomeworkCorrectTeacher(Integer homeworkId, CorrectTeacher correctTeacher) {
        if (correctTeacher == null) {
            return;
        }
        if (StringUtils.isNotEmpty(correctTeacher.getTeacherForSpeaking())) {
            String teacherName = userFeignClient.getUserNameByUserId(correctTeacher.getTeacherForSpeaking());
            hwHomeworkTeacherCorrectMapper.updateUnCorrectListTeacher(homeworkId, QuestionTypeEnum.SPEAKING, correctTeacher.getTeacherForSpeaking(), teacherName);
        }
        if (StringUtils.isNotEmpty(correctTeacher.getTeacherForSubjective())) {
            String teacherName = userFeignClient.getUserNameByUserId(correctTeacher.getTeacherForSubjective());
            hwHomeworkTeacherCorrectMapper.updateUnCorrectListTeacher(homeworkId, QuestionTypeEnum.SUBJECTIVE, correctTeacher.getTeacherForSubjective(), teacherName);
        }
        if (StringUtils.isNotEmpty(correctTeacher.getTeacherForWriting())) {
            String teacherName = userFeignClient.getUserNameByUserId(correctTeacher.getTeacherForWriting());
            hwHomeworkTeacherCorrectMapper.updateUnCorrectListTeacher(homeworkId, QuestionTypeEnum.WRITING, correctTeacher.getTeacherForWriting(), teacherName);
        }

    }

    @Override
    public void updateWhenStudentFinish(Integer homeworkRecordId, String examId, Integer examIdentity, Date endTime, HomeworkStatusEnum status) {
        hwHomeworkTeacherCorrectMapper.updateListFinish(homeworkRecordId, examId, examIdentity, endTime, status);
    }

    @Override
    public Integer getUnCorrectListCount(String teacherId) {
        Integer count = hwHomeworkTeacherCorrectMapper.getUnCorrectListCount(teacherId);
        return count;
    }
}
